<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operation">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <el-table :data="roleList">
        <el-table-column prop="name" align="center" width="200px" label="角色">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editCache.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200px" label="启用">
          <template v-slot=" { row } ">
            <el-switch v-if="row.isEdit" v-model="row.editCache.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editCache.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot=" { row } ">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="onEditComplete(row)">确认</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="assignPermission(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="onEdit(row)">编辑</el-button>
              <template>
                <el-popconfirm
                  title="您确定要删除吗？"
                  @onConfirm="onDelete(row.id)"
                >
                  <el-button slot="reference" style="margin-left:10px;" type="text" size="mini">删除</el-button>
                </el-popconfirm>
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end">
        <el-col :span="6">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="pageParams.total"
            :current-page="pageParams.page"
            :page-size="pageParams.pagesize"
            @current-change="onChangePage"
          />
        </el-col>
      </el-row>
      <!-- 添加角色对话框 -->
      <el-dialog width="500px" title="添加角色" :visible.sync="showDialog" @close="onCancel">
        <el-form ref="formRef" :model="formModel" :rules="rules" label-width="120px">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="formModel.name" style="width: 85%" size="mini" />
          </el-form-item>
          <!-- 如果不需要校验，就不需要prop属性，但是如果没有prop属性，重置表单时该表单项不会重置 -->
          <el-form-item prop="state" label="启用">
            <el-switch v-model="formModel.state" :active-value="1" :inactive-value="0" />
          </el-form-item>
          <el-form-item prop="description" label="角色描述">
            <el-input v-model="formModel.description" style="width: 85%" size="mini" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
                <el-button size="mini" @click="onCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="showPermissionDialog" @close="showPermissionDialog = false">
        <el-tree
          ref="permissionTree"
          :check-strictly="true"
          :data="permissionList"
          node-key="id"
          default-expand-all
          :props="{ label: 'name'}"
          show-checkbox
          :default-checked-keys="permIds"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="onPermissionAssignSuccess">确认</el-button>
            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { roleListService, roleAddService, roleUpdateService, roleDeleteService, roleDetailService } from '@/api/role'
import { permissionListService, permissionAssignService } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      formModel: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      roleList: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      showPermissionDialog: false, // 分配权限对话框的显示与隐藏
      permissionList: [], // 权限列表
      permIds: [], // 选中的权限id
      currentRoleId: null // 当前角色id
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await roleListService(this.pageParams)
      this.roleList = rows
      this.roleList.forEach(role => {
        // 为每一行数据设置isEdit属性，用于控制编辑插槽的显示与隐藏
        // 需要注意的是，这里的isEdit不是响应式的，所以要使用Vue.set()方法来设置isEdit的值
        // role.isEdit = false
        this.$set(role, 'isEdit', false)
        // 为每一行的编辑数据缓存
        this.$set(role, 'editCache', {
          name: role.name,
          state: role.state,
          description: role.description
        })
      })
      this.pageParams.total = total
    },
    onChangePage(page) {
      this.pageParams.page = page
      this.getRoleList()
    },
    onSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          await roleAddService(this.formModel)
          this.$message({
            type: 'success',
            message: '添加角色成功'
          })
          this.onCancel()
          this.getRoleList()
        }
      })
    },
    onCancel() {
      this.showDialog = false
      this.$refs.formRef.resetFields()
    },
    onEdit(row) {
      // console.log('onEdit', row)
      row.isEdit = true
      // 恢复缓存数据
      row.editCache.name = row.name
      row.editCache.state = row.state
      row.editCache.description = row.description
    },
    async onEditComplete(row) {
      if (row.editCache.name && row.editCache.description) {
        await roleUpdateService({
          ...row.editCache,
          id: row.id
        })
        this.$message({
          type: 'success',
          message: '修改角色成功'
        })
        // eslint报错Possible race condition: `row.isEdit` might be reassigned based on an outdated value of `row.isEdit`
        // row.isEdit = false
        Object.assign(row, {
          isEdit: false,
          ...row.editCache
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请输入角色名称和角色描述'
        })
      }
    },
    async onDelete(id) {
      await roleDeleteService(id)
      this.$message({
        type: 'success',
        message: '删除角色成功'
      })
      // 如果当前页只有一条数据且当前页不是第一页，则跳转到前一页
      if (this.roleList.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    async assignPermission(id) {
      this.currentRoleId = id
      // 获取权限列表
      this.permissionList = transListToTreeData(await permissionListService(), 0)
      // 获取当前角色的权限
      const { permIds } = await roleDetailService(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async onPermissionAssignSuccess() {
      // 提交数据
      // 需要注意的是，这里的permIds是单向绑定在权限树组件中的，所以并不会同步更新
      // 可以使用el-tree组件的getCheckedKeys()方法来获取选中的权限id
      await permissionAssignService({
        id: this.currentRoleId,
        permIds: this.$refs.permissionTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.role-operation {
  padding: 20px;
}
</style>
